<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
	
class Enrollment Extends MY_Controller
{
	var $profile_data;
	var $user_data;
	public function __construct()
	{
		parent::__construct();
		$this->load->model(array('M_levels','M_users','M_new_enrollee'));
		$this->load->library(array('authlink','create_captcha','token','hs'));
		$this->_generate_transaction();
		
		
		$this->view_data['browser_name'] = $this->agent->browser();
		$this->view_data['browser_vers'] = $this->agent->version();
		$this->footer = FALSE;

	}
	
	/*
		First part
		Choose if new or old enrollee
	*/
	
	public function index()
	{
		$this->view_data['system_message'] = $this->_msg();
		$this->_check_transaction();
		
		$this->session->set_userdata('enrollment_finished',FALSE);
		$this->session->set_userdata('enrollment_type',NULL);
		$this->session->set_userdata('forenrollagainprep',FALSE);
		$this->session->set_userdata('forenrollagain',FALSE);
		$this->authlink->clear_authlink();
		
		//captcha
		$this->create_captcha->_captcha();
		$captcha = $this->create_captcha->data();
		$this->view_data['question'] = $captcha->image;

		//token
		$this->view_data['token'] = $this->token->get_token();
	}
	
	/*
		Controller that sets all session and transaction and token to avoid tampering of enrollment
		after setting, redirects to OLD/NEW enrollment page
	*/
	public function enrollment_procedure()
	{	
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->form_validation->set_rules('captcha_answer','','trim|htmlspecialchars');
		$this->form_validation->set_rules('level_option','','trim|htmlspecialchars');
		$this->form_validation->set_rules('sdj','','trim|htmlspecialchars');
		//check proper form input
		if($this->input->post('enrollment_type') !== FALSE)
		{
			//check post ID
			if($this->input->post('level_option'))
			{
				//check form token
				if($this->token->validate_token($this->input->post('sdj')))
				{
					if($this->create_captcha->validate($this->input->post('captcha_answer'),TRUE))
					{
						switch($option = $this->input->post('level_option'))
						{
							case $option == 'new':
								$this->session->set_userdata('enrollment_finished',FALSE);
								$this->session->set_userdata('enrollment_type','NEW');
								$this->session->set_userdata('forenrollagainprep',FALSE);
								$this->session->set_userdata('forenrollagain',FALSE);
								$this->_msg('n','Enrolle status Set [NEW], please select level','level');
							break;
							case $option == 'old':
								$this->session->set_userdata('enrollment_finished',FALSE);
								$this->session->set_userdata('enrollment_type','NEW');
								$this->session->set_userdata('forenrollagainprep',FALSE);
								$this->session->set_userdata('forenrollagain',FALSE);
								$this->_msg('n','Enrolle status Set [NEW], please select level','level');
							break;
						}
					}else{
						$this->token->reset();
						$this->_msg('e','Invalid Captcha Answer','enrollment');
					}
				}else{
					$this->_msg('e','Invalid Token','enrollment');
				}
			}else{
				$this->token->reset();
				$this->_msg('e','Please select an option','enrollment');
			}
		}else{
			$this->token->reset();
			$this->_msg('e','Wrong Form Submiut, Please try again','enrollment');
		}
	}
	
	
	/*
		PART 2
		Choose what level and block section
	*/
	public function choose_level_block_section()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['token'] = $this->token->get_token();
		
		if($this->session->userdata('enrollment_finished') ==  FALSE AND $this->session->userdata('enrollment_type') == 'NEW')
		{
			$this->load->helper('misc');
			$this->view_data['levels'] = $this->M_levels->get_all_levels_array();
			
			if($this->input->post('level_section'))
			{
				if($this->token->validate_token($this->input->post('sfe_8892')))
				{
					$this->form_validation->set_rules('grade_level','Grade Level','required');
					$this->form_validation->set_rules('section','Block/Section','required');
				
					if($this->form_validation->run() !== FALSE)
					{

						$grade_level['grade_level'] = $this->input->post('grade_level');
						$grade_level['block'] = $this->input->post('section');
						$this->session->set_userdata('levels',$grade_level);
						$this->_msg('s','Grade Level Set','register');
					}else{
						$this->view_data['system_message'] = $this->_msg('e',validation_errors());
					}
				}else{
					$this->token->reset();
					$this->_msg('e','Token Expired, Try again','level');
				}
			}
		}else{
			$this->_msg('n','Unable to verify transaction, Please Try Again','enrollment');
		}
	}
	
	/*
		PART 3
		Registration FOrm
	*/
	public function registration_form()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['class_error'] = NULL;
		$this->view_data['token'] = $this->token->get_token();
		$this->view_data['enrollagain'] = $this->_forenrollegain();
		
		if($this->session->userdata('enrollment_type') == 'NEW')
		{
			$levels = $this->session->userdata('levels');
			if($levels)
			{
			
				// pd($this->input->post());
				// $_POST['email'] = 'asdfasdf';
				if($this->session->userdata('enrollment_finished') == FALSE)
				{
					$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
					
					//Check if enrollee grade level is preschool,intermediate,highschool etc
					//add other fields
					//this will add additional information fields and set the validation error
					if($this->M_levels->check_for_level_cat($levels['grade_level'],array('preschool')))
					{
						$this->view_data['preschool'] = TRUE;
						$validation = 'enrollment_profile_preschool';
					}elseif($this->M_levels->check_for_level_cat($levels['grade_level'],array('primary')))
					{
						$this->view_data['primary'] = TRUE;
						$validation = 'enrollment_profile_primary';
					}elseif($this->M_levels->check_for_level_cat($levels['grade_level'],array('secondary','gradeschool')))
					{
						$this->view_data['gradeschool'] = TRUE;
						$validation = 'enrollment_profile_gradeschool';
					}elseif($this->M_levels->check_for_level_cat($levels['grade_level'],array('intermediate','highschool')))
					{
						$this->view_data['highschool'] = TRUE;
						$validation = 'enrollment_profile_highschool';
					}else{
						$validation = 'enrollment_profile';
					}
					
					//post has been submitted
					
					if($this->input->post())
					{
						$fillup_profile = $this->input->post('fillup_profile');
						$submit_save_later = $this->input->post('submit_save_later');
						
						if($this->token->validate_token($this->input->post('sdf_loc')))
						{
							$this->form_validation->set_message('required', 'This Field is required');

							if($this->form_validation->run($validation) !== FALSE)
							{
								$profile = $this->input->post();
								
								// pd($profile);
								unset($profile['fillup_profile']);
								if($this->M_users->register_user($profile) == TRUE)
								{
									// $this->load->library('idno_creator');
									// $generated_studentid = $this->idno_creator->generate_new_id_compressed($levels['grade_level']);
									$for_enrollment_table['e_profile_id']  = $this->M_users->get_last_insert_id();
									$for_enrollment_table['e_grade_level'] 	 = $levels['grade_level'];
									$for_enrollment_table['block'] = $levels['block'];
									$for_enrollment_table['e_student_id'] = date('Y').'-0000';
									$for_enrollment_table['e_enrollee_type'] = 'new';
									$for_enrollment_table['enrollment_transaction_code'] = NULL;
									$for_enrollment_table['mustverify'] = NULL;
									
									//insert Enrollee
									if($this->M_new_enrollee->enroll_new_student($for_enrollment_table) == TRUE)
									{
										//insert student id to database for record keeping on used student id's
										// $this->M_new_enrollee->count_id($generated_studentid,$prof['level_id']);
										$enroll_id = $this->M_new_enrollee->get_last_input_id();
										$level_id = $levels['grade_level'];
										$for_enrollment_table['enrollment_id'] = $enroll_id;
										$for_enrollment_table['child_lname'] = $profile['child_lname'];
										$for_enrollment_table['child_fname'] =$profile['child_fname'];
										$for_enrollment_table['child_mname'] =$profile['child_mname'];
										$for_enrollment_table['emailaddress'] =$profile['email'];
										//generate fees
										if($this->M_new_enrollee->get_fees_set_for_current_level($level_id,$enroll_id) !== FALSE)
										{
											if($submit_save_later)
											{
												$save_data_for_later = $this->M_new_enrollee->save_data_for_resume($for_enrollment_table);
												if($save_data_for_later->status == TRUE)
												{
													$fullname = $for_enrollment_table['child_lname'].' '.$for_enrollment_table['child_fname'].' '.$for_enrollment_table['child_mname'];
													$this->_email_student_resume_link($fullname,$for_enrollment_table['emailaddress'],$save_data_for_later->code);
													$this->_msg('s','Registration was successfull. Please Continue','status/saved');
												}else{
													$this->view_data['system_message'] = $this->_msg('e','System was unable to save your data.');
												}
											}elseif($fillup_profile)
											{
												// die('next');
												$this->session->set_userdata('profilesettings',$for_enrollment_table);
												$this->session->set_userdata('enrollmentstep',2);
												$this->_msg('s','Registration was successfull. Please Continue','developmental');
											}
										}
									}	
								}else
								{	
									$auth = $this->authlink->generate_authlink();
									$error_number = time().'-'.uniqid(rand(1000,9999));
									$message ='An Error has occured, System failed to Insert Student: '.$profile['child_fname'].' Error Number: ('.$error_number.')';
									log_message('error',$message);
									$this->_msg('e',$message,'status/error/'.$auth);
								}
							}else{
								if(validation_errors() !== '')
								{
									$this->view_data['system_message'] = $this->_msg('e','Please Fix the errors Below marked with red.');
								}
							}
						}else{
							$this->token->restart();
							$this->_msg('e','Token Expired Or Compromised','register');
						}
					}
				}else{
					redirect('enrollment');
				}
			}else{
				$this->_msg('n','Please select a level','enrollment/choose_level_block_section');
			}
		}else{
			redirect('enrollment');
		}
		
	}
	
	public function developmental_history()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['class_error'] = NULL;
		$this->view_data['token'] = $this->token->get_token();
		$this->view_data['enrollagain'] = $this->_forenrollegain();
		if($this->session->userdata('enrollmentstep') == 2)
		{
			$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
			if($this->form_validation->run('developmental_history') !== FALSE)
			{
				$this->load->helper('misc');
				$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
				
				if($this->input->post('fillup_developmental') !== FALSE)
				{
					if($this->token->validate_token($this->input->post('spm_sdf')))
					{
						$prof = $this->session->userdata('profilesettings');				
						$developmental = $this->input->post();
						unset($developmental['fillup_developmental']);
						$this->session->set_userdata('enrollmentstep',3);
						$this->M_new_enrollee->add_further_profile_value($developmental,$prof['e_profile_id'],'dev');
						$this->_msg('s','Part 2 Completed','health');
					}else{
						$this->token->reset();
						$this->_msg('e','Token Expired Or Compromised','developmental');
					}
				}
			}else{
				if(validation_errors() !== '')
				{
					$this->view_data['system_message'] = $this->_msg('e','Please Fix the errors Below.');
				}
			}
		}else{
			redirect('register');
		}
	}
	
	public function health_history()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['class_error'] = NULL;
		$this->view_data['token'] = $this->token->get_token();
		$this->view_data['enrollagain'] = $this->_forenrollegain();
		$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
		if($this->session->userdata('enrollment_type') == 'NEW')
		{
			$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
			if($this->session->userdata('enrollmentstep') == 3)
			{
				if($this->form_validation->run('healthhistory') !== FALSE)
				{
					$this->load->helper('misc');
					$this->form_validation->set_error_delimiters('<span class="alert-box">', '</span>');
					
					if($this->input->post('fillup_health') !== FALSE)
					{
						if($this->token->validate_token($this->input->post('sdj_lefg')))
						{
							$health = $this->input->post();
							$prof = $this->session->userdata('profilesettings');
							// pd($health);
							unset($health['fillup_health']);
							$this->session->set_userdata('enrollmentstep',4);
							$this->M_new_enrollee->add_further_profile_value($health,$prof['e_profile_id'],'hlth');
							$this->_msg('s','Part 3 completed','done');
						}else{
							$this->token->restart();
							$this->_msg('e','Token Has is expired or has been compromised, Please Restart Again','health');
						}
					}
				}else{
					if(validation_errors() !== '')
					{
						$this->view_data['system_message'] = $this->_msg('e','Please Fix the errors Below.');
					}
				}
			}else{
				redirect('enrollment');
			}
		}else{
			redirect('enrollment');
		}
	}
	
	public function enrollment_finished()
	{
		$this->_check_transaction();
		if($this->session->userdata('enrollmentstep') == 4)
		{
			$prof = $this->session->userdata('profilesettings');
			
			$input['enrollment_transaction_code'] =  substr(base64_encode(sha1(time().rand(10,99).md5(time().rand(100,200)))),0,15);
			$input['mustverify'] = time() + 24*60*60;
			$auth = $this->authlink->generate_authlink();
			
			$enroll_id = $prof['enrollment_id'];
			
			//check if validate by email
			if($this->M_school_settings->check_email_verification() == TRUE)
			{
				if($this->M_new_enrollee->finish_enrollment($input,$enroll_id))
				{
					$id = $enroll_id.'_'.rand(1000,9999);
					$c_auth = $this->authlink->hash_make($enroll_id.$id.$input['enrollment_transaction_code']);
					$link = site_url('confirm/validate/'.$id.'/'.$input['enrollment_transaction_code'].'/'.$c_auth);

					$this->_email_student_confirmation_link(
						$prof['child_lname'],
						$prof['child_fname'],
						$prof['child_mname'],
						$link,
						$prof['emailaddress']
					);
					
					$this->token->destroy_token();
					$this->session->set_userdata('enrollmenttransaction',FALSE);
					$this->session->set_userdata('profilesettings',FALSE);
					$this->_msg('s','Enrollment was successfull','status/success/'.$auth);
				}else{
					show_error('System Has encountered an error while finishing enrollment.');
				}
			}else{
				$input['verified'] = 1;
				if($this->M_new_enrollee->finish_enrollment($input,$enroll_id))
				{
					$this->_msg('s',$message,'status/success/'.$auth);
				}else{
					show_error('System Has encountered an error while finishing enrollment.');
				}
			}
		}else{
			redirect('health');
		}
	}
	
	private function _forenrollegain()
	{
		$p_id = $this->session->userdata('forenrollagainprep');
		
		if($p_id !== FALSE)
		{
			return $this->M_new_enrollee->get_recent_insert_profile($p_id);
		}else{
			return FALSE;
		}
	
	
	}
	
	
	
/*############################################## OLD STUDENT ENROLLEE ################################################################## */	

	public function old_enrollee()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->load->library('token');
		$this->token->set_token();
		$this->view_data['form_token'] = $this->token->get_token();
		if($this->input->post('old_enrollee'))
		{
			if($this->token->validate_token($this->input->post('form_token')) == TRUE)
			{
				$this->form_validation->set_rules('idno','ID Number','required|alpha_dash_space');
				
				if($this->form_validation->run() !== FALSE)
				{
					$this->load->model('M_old_enrollee','moe');
					
					$the_id = trim(htmlspecialchars($this->input->post('idno')));
					$result = $this->moe->check_student_id($the_id);
					if($result['status'] == TRUE)
					{
						$this->session->set_userdata(array('e_id'=>$result['enrollment_id'],'p_id'=>$result['profile_id']));
						$hash = $this->authlink->hash_make($the_id);
						$auth = $this->authlink->generate_authlink();
						redirect('enrollment/verify/old/'.$the_id.'/'.$auth.'/'.$hash);
					}else{
						$this->view_data['system_message'] = $this->_msg('n',$result['log']);
					}
				
				}
				if(validation_errors() !== '')
				{
					$this->view_data['system_message'] = $this->_msg('e',validation_errors());
				}
			}else{
				$this->view_data['system_message'] = $this->_msg('e','Invalid Token Submit!');
			}
		}else{
			$this->view_data['system_message'] = $this->_msg('n','Old Students, please enter your ID Number to enroll.');
		}
	}
	
	
	public function verify($type=FALSE,$student_id=FALSE,$auth=FALSE,$hash=FALSE)
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		if($this->authlink->verify_authlink($auth) AND $this->authlink->check_hash_make($student_id,$hash) AND $type AND $student_id)
		{
			$this->view_data['system_message'] = $this->_msg();
			$this->load->library('token');
			$this->view_data['question'] = $this->quest_captcha->get_question();
			$this->view_data['form_token'] = $this->token->get_token();
			$this->view_data['student_id'] = $student_id;
			$this->view_data['auth'] = $auth;
			$this->view_data['hash'] = $hash;
		
			if($this->input->post('verify_old_enrollee'))
			{
				if($this->token->validate_token($this->input->post('form_token')))
				{
					if($this->quest_captcha->check_answer($this->input->post('captcha_answer')))
					{
						$this->form_validation->set_rules('fname','Firstname','required');
						$this->form_validation->set_rules('lname','Lastname','required');
						$this->form_validation->set_rules('password','Password','required');
					
						if($this->form_validation->run() !== FALSE)
						{
							$this->load->model('M_old_enrollee','moe');
							$this->load->model('M_users','mu');
							
							$student_input['fname'] = $this->input->post('fname');
							$student_input['lname'] = $this->input->post('lname');
							$student_input['password'] = $this->input->post('password');

							$search_student = (object)$this->moe->verify_student_credentials($student_input,$student_id);
							
							if($search_student->status == TRUE)
							{
								//insert enrollee to enrollments table and update enrollee archive status
								$result = $this->moe->create_old_enrollee($student_id);
								if($result->status == TRUE)
								{
									$e = $this->moe->return_data();
									if($this->M_new_enrollee->get_fees_set_for_current_level($e->level_id,$e->id,$this->current_grading_period,$this->current_school_year))
									{
										$this->quest_captcha->reset_question();
										$this->_msg('s',$result->log,'enrollment');
									}else{
										$this->authlink->clear_authlink();
										$this->quest_captcha->reset_question();
										$this->_msg('n','You are now registered and an error occured while attempting to calculate your fees.','enrollment');
									}
								}else{
									$this->quest_captcha->reset_question();
									$this->_msg('n',$result->log,'enrollment/verify/'.array_url(array($type,$student_id,$auth,$hash)));
								}
							}
							else{
								$this->quest_captcha->reset_question();
								$this->_msg('e','Credentials entered did not match any from our database.','enrollment/verify/'.array_url(array($type,$student_id,$auth,$hash)));
							}	
						}
					}else{
						$this->quest_captcha->reset_question();
						$this->_msg('e','Wrong Captcha Answer.','enrollment/verify/'.array_url(array($type,$student_id,$auth,$hash)));
					}
				}
			}
		}else{
			echo 'Not ok';
		}
	}
	
	
	/*############################################## END OLD STUDENT ENROLLEE ################################################################## */	

	
	/* +-----------------------------------------------------
	   | Misc methods used for enrollment
	   +----------------------------------------------------
	*/
	
	private function _email_student_confirmation_link($last_name,$first_name,$middle_name,$link,$email_add)
	{
		$school_name = ucwords($this->school_name);
		$school_name_title = $this->_accronymizer($this->school_name).'@DONOTREPLY.com';
		$fullname = strtoupper($first_name.'-'.$middle_name.'-'.$last_name);
		
		$data['school_name'] = $school_name;
		$data['link'] = $link;
		$data['name'] = $fullname;
		
		$message = $this->load->view('email_layouts/template',$data,TRUE);
		
		$this->load->library('email');
		
		$this->email->initialize(array( 
		   'mailtype' => 'html', 
		)); 
		
		
		$this->email->from($school_name_title,'Online Enrollment');
		$this->email->to($email_add);
		$this->email->subject('Please Verify Your Enrollment!');
		$this->email->message($message);
		$this->email->send();
	}
	
	private function _email_student_resume_link($fullname,$email,$code)
	{
		$school_name = ucwords($this->school_name);
		$school_name_title = $this->_accronymizer($this->school_name).'@DONOTREPLY.com';
		
		$data['school_name'] = $school_name;
		$data['link'] = site_url('enrollment/resume_enrollment');
		$data['name'] = $fullname;
		$data['code'] = $code;
		
		$message = $this->load->view('email_layouts/resume_enrollment',$data,TRUE);
		
		
		// echo $message;
		// die();
		$this->load->library('email');
		
		$this->email->initialize(array( 
		   'mailtype' => 'html', 
		)); 
		
		
		$this->email->from($school_name_title,'Pause Enrollment');
		$this->email->to($email);
		$this->email->subject('Enrollment was Paused.');
		$this->email->message($message);
		$this->email->send();
	}
	
	private function _accronymizer($string = FALSE)
	{
		if($string !== FALSE)
		{
			$clean_string = htmlspecialchars(strip_tags($string));
			$number_of_words = str_word_count($clean_string,1);
			function acc($x)
			{
				if(strlen($x) > 1)
				{
					return $x[0];
				}
			}
			$accronym = array_map("acc",$number_of_words);
			return strtoupper(implode('',$accronym));
		}else{
			return NULL;
		}
	}
	
	private function _check_transaction()
	{
		if($this->session->userdata('enrollmenttransaction') == $this->_generate_transaction())
		{
		
		}else{
			$this->session->sess_destroy();
			redirect();
		}
	}
	
	private function _generate_token()
	{
		$key = "aIradhznlpsVeRae7qztven9lBNwUphE";
		$salt = sha1(date('d-d-d-d-d_d_d_d_d-d-d-d',time()).$key);
		$hash = str_pad($salt,5,'-');
		return $hash;
	}
	
	private function _generate_transaction()
	{
		if($this->session->userdata('enrollmenttransaction') == FALSE)
		{
			$this->session->userdata('enrollmenttransaction',$this->_generate_token());
		}
	}
	
	public function enrollagain($hash = '')
	{
		$this->disable_browser_cache = TRUE;
		$hash = $this->hs->decrypt($hash);
		if($hash)
		{
			$profileid = $this->session->userdata('forenrollagain');
			
			if($profileid)
			{
				$this->session->set_userdata('forenrollagain','');
			}
			
			$this->session->set_userdata('enrollment_finished','');
			$this->session->set_userdata('enrollment_type','');
			
			
			$this->session->set_userdata('forenrollagainprep',$profileid);
			
			// vd($this->session->userdata('forenrollagainprep'));
			$this->session->set_userdata('enrollment_finished',FALSE);
			$this->session->set_userdata('enrollment_type','NEW');
			$this->session->set_userdata('enrollagain',TRUE);
			
			$this->_msg('n','Hello, Please select a grade level.','level');
		}else{
			redirect('enrollment');
		}
	}
	
	public function quitenrollment()
	{
		$this->session->sess_destroy();
		redirect('enrollment');
	}
	
	public function resume_enrollment()
	{
		$this->footer = false;
		$this->view_data['token'] = $this->token->get_token(); // form token
		$this->load->helper('file');//load helper file
	
		if($this->input->post('continue_enrollment'))
		{
			if($this->token->validate_token($this->input->post('skd_kkl')))
			{
				if($this->create_captcha->validate($this->input->post('captcha_code'),TRUE))
				{
					$this->form_validation->set_rules('resume[security_code]','Security Code','strip_tags|required|htmlspecialchars');
					$this->form_validation->set_rules('resume[email]','Email','strip_tags|required|valid_email|htmlspecialchars');
					$this->form_validation->set_rules('skd_kkl','Form Error','strip_tags|required|htmlspecialchars');
					
					if($this->form_validation->run() !== FALSE)
					{
						
						$result = $this->M_new_enrollee->get_resume_credentials_for_resume_enrollment($this->input->post());
						
						if($result !== FALSE)
						{
							$date = intval(dateTime::createFromFormat('Y-m-d',date('Y-m-d'))->format('U'));
						
							$ed = intval($result->e_id);
							$pd = intval($result->profile_id);
							$ld = intval($result->level_id);
							
							$hash = $this->hs->encrypt($ed,$pd,$ld,$date);
							$hash2 = 'transaction_no'.sha1($hash.config_item('encryption_key')).'.aspx';
							
							if($hash)
							{
								$this->_msg('s','Saved Data Found,Successfully Created Resume Enrollment Form.','enrollment/resume/'.$hash.'/'.$hash2);
							}else{
								$this->session->set_flashdata('saved_input',$this->input->post('resume'));
								$this->_msg('e','Unable to Generate secure key','enrollment/resume_enrollment/');
							}
						}else{
							$this->token->reset();
							$this->create_captcha->reset();
							$this->session->set_flashdata('saved_input',$this->input->post('resume'));
							$this->_msg('e','The data you provided returned no items.','enrollment/resume_enrollment');	
						}
					}else{
						$this->token->reset();
						$this->create_captcha->reset();
						$this->session->set_flashdata('saved_input',$this->input->post('resume'));
						$this->_msg('e',validation_errors(),'enrollment/resume_enrollment');
					}
				}else{
					$this->token->reset();
					$this->create_captcha->reset();
					$this->session->set_flashdata('saved_input',$this->input->post('resume'));
					$this->_msg('e','Captcha Verification Failed','enrollment/resume_enrollment');
				}
			
			}else{
				$this->token->reset();
				$this->create_captcha->reset();
				$this->session->set_flashdata('saved_input',$this->input->post('resume'));
				$this->_msg('e','Form Session Expired, Please Try Again','enrollment/resume_enrollment');
			}
		}else{
			//if no post then create brand new captcha every refresh
			$this->create_captcha->sessionname('captcha')->_captcha();
			$captcha = $this->create_captcha->data();
			$this->view_data['question'] = $captcha->image;
			$this->view_data['system_message'] = $this->_msg();
			$this->view_data['saved_input'] = $this->session->flashdata('saved_input');
		}
	}
	
	public function resume($hash = FALSE,$hash2 = FALSE)
	{
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['token'] = $this->token->get_token(); // form token
		$x = $this->hs->decrypt($hash);
		if($x AND ('transaction_no'.sha1($hash.config_item('encryption_key')).'.aspx') == strtolower($hash2))
		{
			$ed = $x[0];
			$pd = $x[1];
			$ld = $x[2];
			
			if($this->M_new_enrollee->verify_resume_if_not_from_cache($ed,$pd))
			{
				$this->view_data['sse'] = $this->M_new_enrollee->get_student_resume_data($ed,$pd);
				$this->view_data['hash'] = $hash;
				$this->view_data['hash2'] = $hash2;
				
				if($this->M_levels->check_for_level_cat($ld,array('preschool')))
				{
					$this->view_data['preschool'] = TRUE;
					$validation = 'preschool';
				}elseif($this->M_levels->check_for_level_cat($ld,array('primary')))
				{
					$this->view_data['primary'] = TRUE;
					$validation = 'primary';
				}elseif($this->M_levels->check_for_level_cat($ld,array('secondary','gradeschool')))
				{
					$this->view_data['gradeschool'] = TRUE;
					$validation = 'secondary';
				}elseif($this->M_levels->check_for_level_cat($ld,array('intermediate','highschool')))
				{
					$this->view_data['highschool'] = TRUE;
					$validation = 'highschool';
				}else{
					$validation = 'none';
				}
				
				
				$this->load->config('form_validation_custom');
				$rules = $this->config->item($validation);
				$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
				
				$this->form_validation->set_rules($rules);
				// vd(array_values($rules));
				if($this->input->post())
				{
					if($this->input->post('fillup_profile'))
					{
						if($this->form_validation->run($rules) !== FALSE)
						{
							$post = $this->input->post();
							$result= $this->M_new_enrollee->finish_resumed_enrollment($post,$ed,$pd);
							
							if($result)
							{
								$prof['child_lname'] = $post['child_lname'];
								$prof['child_fname'] = $post['child_fname'];
								$prof['child_mname'] = $post['child_mname'];
								$prof['emailaddress'] = $post['email'];
								$prof['enrollment_id'] = $ed;
								
								
								
								$this->session->set_userdata('profilesettings','');
								$this->session->set_userdata('profilesettings',$prof);
								$this->session->set_userdata('enrollmentstep',4);
								$this->session->set_userdata('forenrollagain',$pd);
								// pd('Now What?');
								$this->_msg('s','Enrollment Successfully Processed.','enrollment/enrollment_finished');
							}else{
								$this->_msg('n','Unable to finsihe Enrollment','enrollment/resume/'.$hash.'/'.$hash2);
							}
						}else{
							$this->view_data['system_message'] = $this->_msg('e','Please Fix the errors below, Note the red mark will not automaticaly disappear.');
						}
					}elseif($this->input->post('submit_save_later'))
					{
						$post = $this->input->post();
						$filter1 = array_map('trim',$post);//trim all values
						$filter2 = array_map('strip_tags',$filter1); //remove tags
						$clean = array_map('htmlspecialchars',$filter2); // encode html
						
						if($this->M_new_enrollee->save_enrollment_for_later($clean,$pd))
						{
							$this->_msg('s','Data Successfully saved.','enrollment/resume/'.$hash.'/'.$hash2);
						}else{
							$this->view_data['system_message'] = $this->_msg('n','No Changes Were made.');
							// $this->_msg('e','Data Successfully saved.','enrollment/resume/'.$hash.'/'.$hash2);
						}
					
					}else{
						
						show_error('Unable to Retrieve form.');
					}
				}
			}else{
				show_error('The Enrollment Transaction for this Security Code is already Finished.');
			}
		}else{
			$this->_msg('e','Security Link Verification Failed.','enrollment/resume_enrollment');
		}
	
	}
	
	public function migrate()
	{
		$this->migrate->current();
	}
}